package com.my.lucky7.controller;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.my.lucky7.common.ApiResult;
import com.my.lucky7.entity.GalleryImage;
import com.my.lucky7.service.GalleryImageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/images")
@Slf4j
public class GalleryImageController {
    private final GalleryImageService service;

    public GalleryImageController(GalleryImageService service) {
        this.service = service;
    }

    @PostMapping
    public ResponseEntity<GalleryImage> createImage(@RequestBody GalleryImage image) {
        return ResponseEntity.ok(service.createImage(image));
    }

    @GetMapping
    public ResponseEntity<ApiResult> getAllImages() {
        return ResponseEntity.ok(ApiResult.success(service.getAllImages()));
    }

    @GetMapping("/getImageByDesc")
    public ResponseEntity<ApiResult> getImageByDesc(String desc) {
        return ResponseEntity.ok(ApiResult.success(service.getImageByDesc(desc)));
    }

    @GetMapping("/{id}")
    public ResponseEntity<GalleryImage> getImageById(@PathVariable Integer id) {
        return service.getImageById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PutMapping("/{id}")
    public ResponseEntity<GalleryImage> updateImage(
            @PathVariable Integer id, 
            @RequestBody GalleryImage updatedImage) {
        return ResponseEntity.ok(service.updateImage(id, updatedImage));
    }

    @GetMapping("/getIndexImage")
    public ResponseEntity<ApiResult> getIndexImage() {
        return ResponseEntity.ok(service.getIndexImage());
    }

    // 2. 表单提交接口
    @PostMapping("/submit")
    public ApiResult submitGallery(
            @RequestBody GalleryImage submissionData,
            @RequestHeader("Authorization") String authorizationHeader) {

        // 1. 验证JWT Token（示例验证逻辑，实际应结合Spring Security）
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            return ApiResult.fail("Missing or invalid Authorization header");
        }

        String token = authorizationHeader.substring(7); // 移除"Bearer "前缀
        // 验证token
        if (!token.equals("901115")) {
            return ApiResult.fail("Missing or invalid Authorization header");
        }

        // 4. 验证请求数据
        if (submissionData.getDescription() == null ||
                submissionData.getDescription().trim().isEmpty()) {
            return ApiResult.fail("Description cannot be empty");
        }

        if (submissionData.getGalleryCreatedAt() == null) {
            return ApiResult.fail("Gallery creation time is required");
        }

        // 5. 处理业务逻辑（示例）
        try {
            // 这里可以添加：
            // - 数据库保存逻辑
            // - 业务校验逻辑
            // - 第三方服务调用等
            return ApiResult.success(service.createImage(submissionData));

        } catch (Exception e) {
            log.error("Error processing submission: {}", ExceptionUtil.getMessage(e));
            return ApiResult.fail(("Server error: " + e.getMessage()));
        }
    }
}